package com.tepth.remote.control.service.alarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.blankj.utilcode.util.ServiceUtils;
import com.tepth.remote.control.base.event.RequestLocationEvent;
import com.tepth.remote.control.service.ControlService;
import com.tepth.remote.control.service.job.ControlCheckJob;
import com.tepth.remote.core.app.Control;

import org.greenrobot.eventbus.EventBus;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/12/25
 */
public class ControlAlarmReceiver extends BroadcastReceiver {

    public static final String ALARM_ACTION = "com.tepth.remote.control.service.alarm.CONTROL_ALARM";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ALARM_ACTION.equals(intent.getAction())) {
            final Intent i = new Intent();
            i.setAction(ALARM_ACTION);
            final AlarmManager alarmManager = Control.getAlarmManager();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
                        15 * 60 * 1000,
                        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP,
                        15 * 60 * 1000,
                        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            } else {
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        15 * 60 * 1000, 15 * 60 * 1000,
                        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            }
            if (!ServiceUtils.isServiceRunning(ControlCheckJob.CONTROL_SERVICE_NAME)) {
                final Intent serviceIntent = new Intent(context, ControlService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(serviceIntent);
                } else {
                    context.startService(serviceIntent);
                }
            } else {
                EventBus.getDefault().post(new RequestLocationEvent());
            }
        }
    }
}
